<script setup>
import { computed, ref } from "vue";
import { useCounterStore } from "./stores/counter";
const store = useCounterStore();

const items = computed(() => store.items);

// 计算已选商品数量和总价
const selectedItems = computed(() =>
  items.value.filter((item) => item.selected)
);
const totalSelected = computed(() =>
  selectedItems.value.reduce((total, item) => total + item.price * item.num, 0)
);

// 多选框
const All = (event) => {
  items.value.forEach((item) => (item.selected = event.target.checked));
};

// 删除
const removeItem = (item) => {
  const index = store.items.findIndex((i) => i.id === item.id);
  if (index !== -1) {
    store.items.splice(index, 1);
  }
};

// 增加和减少
const jia = (item) => {
  store.jia(item);
};
const jian = (item) => {
  store.jian(item);
};
</script>

<template>
  <div>
    <table>
      <thead>
        <tr>
          <th><input type="checkbox" @change="All" /></th>
          <th>商品</th>
          <th>单价</th>
          <th>数量</th>
          <th>小计</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in items" :key="item.id">
          <td><input type="checkbox" v-model="item.selected" /></td>
          <td>{{ item.sp }}</td>
          <td>{{ item.price }}</td>
          <td>
            <button @click="jian(item)">-</button>
            {{ item.num }}
            <button @click="jia(item)">+</button>
          </td>
          <td>{{ item.price * item.num }}</td>
          <td><button @click="removeItem(item)">删除</button></td>
        </tr>
      </tbody>
    </table>
    <div>
      <p>
        已选 {{ selectedItems.length }} 件商品，总价：{{ totalSelected }} 元
      </p>
    </div>
  </div>
</template>
